from modules.common import d_common
import gettext
from modules.common import getsource
from common.iniconfig import iniconfig
import urllib2,urllib
import os,re,zipfile
from common.read.play import dict_play
import cPickle as p
import md5
import sys
from modules.common import delete_file_folder
from modules.Chinese_Chinese.dict_Chinese_Chineseoption import dict_Chinese_Chineseoption

class d_Chinese_Chinese_re:
    word=""
    pr=""
    ct=""
    dt=""
    bk=""
    ph=""
    bh=""
    zx=""
    def __init__(self,word):
	for uchar in word.replace(" ",""):
	    if not(uchar >= u'\u4e00' and uchar<=u'\u9fa5'):
		raise UnicodeError
	self.word=word
    
    def __del__(self):
	pass
    
    def get_pr(self):
	return self.pr
    
    def _get_pr(self,source):
	c=source.find('<div id="pronounce">')
	if c==-1:
	    self.pr=""
	    return
	a=source.find("</strong><span><b>",c)
	b=source.find("</b>",a)
	if a!=-1:
	    self.pr=source[a+18:b]
    
    def _get_ct(self,source):
	a=source.find('<div class="tab cn-basicmean dict-cn-basicmean-char" id="cn-basicmean">')
	b=source.find('<div class="source">',a)
	if a!=-1:
	    self.ct=source[a:b]
	else:
	    a=source.find('<div class="tab cn-basicmean dict-cn-basicmean-word" id="cn-basicmean">')
	    b=source.find('<div class="source">',a)	
	    if a==-1:
		self.zx=""
		return	    
	    self.ct=source[a:b]
	pattern=re.compile(r'''<a href="#[0-9]*">''')
	self.ct=pattern.sub(" ",self.ct).replace("]","]&nbsp;&nbsp;&nbsp;")	
    def get_ct(self):
	return self.ct
    
    def _get_dt(self,source):
	a=source.find('<div class="tab cn-detailmean dict-cn-detailmean-char" id="cn-detailmean">')
	b=source.find('<div class="source">',a)
	if a!=-1:
	    self.dt=source[a:b]
	else:
	    a=source.find('<div class="tab cn-detailmean dict-cn-detailmean-word" id="cn-detailmean">')
	    b=source.find('<div class="source">',a)	
	    if a==-1:
		self.zx=""
		return	    
	    self.dt=source[a:b]
	    pattern=re.compile(r'''<a href="#[0-9]*">''')
	    self.dt=pattern.sub(" ",self.dt).replace("]","]&nbsp;&nbsp;&nbsp;")	    
    def get_dt(self):
	return self.dt
    
    def _get_ph(self,source):
	a=source.find('<div class="tab cn-phrase dict-cn-phrase-char" id="cn-phrase">')
	b=source.find('<div class="source">',a)
	if a!=-1:
	    self.ph=source[a:b]
	else:
	    a=source.find('<div class="tab cn-phrase dict-cn-phrase-word" id="cn-phrase">')
	    b=source.find('<div class="source">',a)
	    if a==-1:
		self.zx=""
		return	    
	    self.ph=source[a:b]
	    
    def get_ph(self):
	return self.ph
    
    def _get_bh(self,source):
	a=source.find('<div class="tab cn-strokes dict-cn-strokes-char" id="cn-strokes">')
	b=source.find('<div class="source">',a)
	if a!=-1:
	    self.bh=source[a:b]
	else:
	    a=source.find('<div class="tab cn-strokes dict-cn-strokes-word" id="cn-strokes">')
	    b=source.find('<div class="source">',a)
	    if a==-1:
		self.zx=""
		return	    
	    self.bh=source[a:b]
	    
    def get_bh(self):
	return self.bh
    
    def _get_bk(self,source):
	a=source.find('<div class="tab cn-baike-mean dict-cn-baikemean-char" id="cn-baike-mean">')
	b=source.find('</div>',a)
	if a!=-1:
	    self.bk=source[a:b]+"</div></div>"
	else:
	    a=source.find('<div class="tab cn-baike-mean baike-cn-baikemean-word" id="cn-baike-mean">')
	    b=source.find('</div>',a)	
	    if a==-1:
		self.zx=""
		return
	    self.bk=source[a:b]+"</div></div>"
	    
    def get_bk(self):
	return self.bk
    
    def _get_zx(self,source):
	a=source.find('<div class="tab cn-font dict-cn-font-char" id="cn-font">')
	b=source.find('<div class="source">',a)
	if a!=-1:
	    self.zx=source[a:b]
	else:
	    a=source.find('<div class="tab cn-font dict-cn-font-word" id="cn-font">')
	    b=source.find('<div class="source">',a)	  
	    if a==-1:
		self.zx=""
		return
	    self.zx=source[a:b]
	    
    def get_zx(self):
	return self.zx
    
    def analyse(self):
	url="http://dict.baidu.com/s?wd=%s" % self.word
	url=url.encode('utf-8')
	url=urllib2.unquote(url)
	source=unicode(urllib2.urlopen(url).read(),"utf-8")	

	self._get_pr(source)
	self._get_ct(source)
	self._get_dt(source)
	self._get_bk(source)
	self._get_ph(source)
	self._get_bh(source)
	self._get_zx(source)
	
    def __getitem__(self,key):
	if key=="Word":
	    return self.word
	if key=="Pronounce":
	    return self.pr
	if key=="Phrases":
	    return self.ph
	if key=="Strokes":
	    return self.bh
	if key=="Font":
	    return self.zx
	if key=="Concise translate":
	    return self.ct
	if key=="Detailed translate":
	    return self.dt
	if key=="Baike":
	    return self.bk	
    
class d_Chinese_Chinese(d_common):
    cont=[]
    cont_en=[]
    def __init__(self):
	d_common.__init__(self,_("Chinese_Chinese"),_("all data is from baidu"),_("hzh"),_("v1.0.0"),_("2013-2-22"))
	self.cont.append(_("Word"))
	self.cont.append(_("Pronounce"))
	self.cont.append(_("Concise translate"))
	self.cont.append(_("Detailed translate"))
	self.cont.append(_("Baike"))
	self.cont.append(_("Phrases"))
	self.cont.append(_("Strokes"))
	self.cont.append(_("Font"))
    
	self.cont_en.append("Word")
	self.cont_en.append("Pronounce")
	self.cont_en.append("Concise translate")
	self.cont_en.append("Detailed translate")
	self.cont_en.append("Baike")
	self.cont_en.append("Phrases")
	self.cont_en.append("Strokes")
	self.cont_en.append("Font")
	    
	self.Chinese_Chinese_ini=iniconfig("modules/Chinese_Chinese/settings")
	pathzip="modules/Chinese_Chinese/downloads/Chinese_Chinese_data.zip"
	if not os.path.exists(pathzip):
	    tmp=zipfile.ZipFile(pathzip,"w")
	    tmp.close()
	    self.zip_file=zipfile.ZipFile(pathzip,"a")
	    self.zip_list=self.zip_file.namelist()
	else:
	    self.zip_file=zipfile.ZipFile(pathzip,"a")
	    self.zip_list=self.zip_file.namelist()
		    
    def __del__(self):
	try:
	    self.zip_file.close()
	    delete_file_folder("modules/Chinese_Chinese/downloads","Chinese_Chinese_data.zip")
	except Exception,e:
	    pass
	    
    def __str__(self):
	return d_common.__str__(self)
	
    def setoption(self,op,val):
	self.Chinese_Chinese_ini.set_item(op,val)
		
    def getoption(self,op):
	return self.Chinese_Chinese_ini.get_item(op)
	    
    def setoptiongui(self,parent):
	a=dict_Chinese_Chineseoption(parent)
	a.ShowModal()
    def getmp3(self,word,parent):
	        parent.m_statusBar1.SetStatusText(_("'%s' has no mp3 sound.") % word,0)
		return
                read=dict_play(parent)
		path="modules/Chinese_Chinese/downloads/%s.mp3" % word
		name=word+".mp3"
		if not os.path.exists(path):
			if name in self.zip_list:
				self.zip_file.extract(name,"modules/Chinese_Chinese/downloads/")
			else:
				url="http://dict.baidu.com/s?wd=%s" % word
	                        url=url.encode('utf-8')
	                        url=urllib2.unquote(url)
	                        source=unicode(urllib2.urlopen(url).read(),"utf-8")
				pattern=re.compile(r'''<a href="#"\s*url="([^>]*).mp3"\s*>''')
				match=pattern.findall(source)
				if match:
					match[0]=match[0].replace("\n","")
					match[0]=match[0].replace("\r","")						
					urllib.urlretrieve(match[0]+".mp3", path)					
 
			
		if os.path.exists(path):
			parent.m_statusBar1.SetStatusText(_("'%s' is reading")% word,0)
			fil=file(path,"rb")
			fil2=file("modules/Chinese_Chinese/temp/temp.mp3","wb")
			fil2.write(fil.read())
			fil.close()
			fil2.close()
			read.read(os.getcwd()+"/modules/Chinese_Chinese/temp/temp.mp3".replace("/",os.path.sep))
			os.remove("modules/Chinese_Chinese/temp/temp.mp3")
			if self.getoption("auto_save").strip()=="1":	
				if name in self.zip_file.namelist():	
					return
				self.zip_file.write(path,name,zipfile. ZIP_DEFLATED)
				
		else:
			parent.m_statusBar1.SetStatusText(_("'%s' has no mp3 sound.") % word,0)	
		del read
    def get_li(self,name,str):
	if str==None:
	    return ""
	if str.strip()=="":
	    return ""
	else:
	    if name==self.cont[1]:
		return '''<li><br/>%s</li>''' % str
	    else:
		return '''<li><font color=Blue><h3>%s</h3></font><br/>%s</li>''' % (name,str)

    def getwordlist(self):
	a=open("modules/Chinese_Chinese/words.txt","r")
	b=[]
	for i in a.readlines():
	    b.append(unicode(i,"gb2312"))
	a.close()
	return b
    def getcontentHTML(self,word):
	path="modules/Chinese_Chinese/downloads/%s" % word
	if os.path.exists(path):
	    temp2=file(path,"r")
	    temp=p.load(temp2)
	    temp2.close()
	else:
	    if word in self.zip_file.namelist():
		self.zip_file.extract(word,"modules/Chinese_Chinese/downloads/")
		temp3=file(path,"r")
		temp=p.load(temp3)
		temp3.close()		    
	    else:
		temp=d_Chinese_Chinese_re(word)
		temp.analyse()					
		
		
	a='''<h1>%s</h1><br/>
		%s
		<ul>
		%s%s%s%s%s%s
		</ul>
		''' % (temp[self.cont_en[0]],
		       self.get_li(self.cont[1],temp[self.cont_en[1]]),
		       self.get_li(self.cont[2],temp[self.cont_en[2]]),
		       self.get_li(self.cont[3],temp[self.cont_en[3]]),
		       self.get_li(self.cont[4],temp[self.cont_en[4]]),
		       self.get_li(self.cont[5],temp[self.cont_en[5]]),
		       self.get_li(self.cont[6],temp[self.cont_en[6]]),
		       self.get_li(self.cont[7],temp[self.cont_en[7]]))
	if self.getoption("auto_save").strip()=="1":
	    if word in self.zip_file.namelist():
		return a
			
	    b={self.cont_en[0]:temp.word,self.cont_en[1]:temp.pr,self.cont_en[2]:temp.ct
			              ,self.cont_en[3]:temp.dt,self.cont_en[4]:temp.bk,self.cont_en[5]:temp.ph
			              ,self.cont_en[6]:temp.bh,self.cont_en[7]:temp.zx}
	    self.zip_file.writestr(word,p.dumps(b),zipfile.ZIP_DEFLATED)
	    self.zip_list.append(word)
	    del b
	return a
	    
    def download(self,input,output,has_mp3,append,word_start=0,mp3_start=0):
	    if has_mp3:
		print _("\n**warning:Chinese_Chinese dict doesn't support downloading mp3 files.**\n")
	    if append:
		    tmp=zipfile.ZipFile(output,"a")
	    else:
		    tmp=zipfile.ZipFile(output,"w")
		    if os.path.exists(output+".project"):
			    os.remove(output+".project")
	    hehe=iniconfig(output+".project")	
	    a=open(input,"r")
	    b=a.readlines()
	    allnums=len(b)
	    for i in range(0,allnums):
		b[i]=unicode(b[i],"gb2312")
	    if hehe.get_item("word")!="":
		    if str(md5.new(a.read()).digest())!= hehe.get_item("md5"):
			    print _("\n**error:Project file %s refers to another file,please remove it.**\n") % output+".project"
			    return
		    word_start=string.atoi(hehe.get_item("word"))
	    else:
		    hehe.set_item("md5",str(md5.new(a.read()).digest()))
	    a.close()	
	    print _("Begin downloading words' data\n")
	    try:
		    for c in range(word_start,allnums):
			    b[c]=b[c].strip()
			    if b[c]=="":
				    continue
			    percent=100*(c+1)/allnums
			    print _("current word:")+b[c]+" "*(25-len(b[c])) +_("percent:")+str(percent)+"%",
			    sys.stdout.write("\r")
			    try:
				    temp=d_Chinese_Chinese_re(b[c])
				    temp.analyse()			
				    d={self.cont_en[0]:temp.word,self.cont_en[1]:temp.pr,self.cont_en[2]:temp.ct
			              ,self.cont_en[3]:temp.dt,self.cont_en[4]:temp.bk,self.cont_en[5]:temp.ph
			              ,self.cont_en[6]:temp.bh,self.cont_en[7]:temp.zx}		
				    tmp.writestr(b[c],p.dumps(d),zipfile. ZIP_DEFLATED)
			    except KeyboardInterrupt,e:
				    print _("\nDownload is canceled by user.\n")
				    tmp.close()
				    return			    
			    except:
				    pass
			    hehe.set_item("word",str(c+1))
		    print _("\nAll words' data downloads successfully!\n")
		    print _("In all, the zip file should be placed in modules/Chinese_Chinese/downloads directory,\nand named 'Chinese_Chinese_data.zip'\n")
	    except KeyboardInterrupt,e:
		    print _("\nDownload is canceled by user.\n")
		    tmp.close()
		    return
	    os.remove(output+".project")
	    tmp.close()